package info.johnwheeler.gaestorage.core;

import java.util.ArrayList;

import com.google.appengine.api.datastore.QueryResultIterator;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.googlecode.objectify.util.DAOBase;

public class PersonDao extends DAOBase {

    static {
        ObjectifyService.register(Person.class);
    }

    public Person save(Person person) {
        ofy().put(person);
        return person;
    }
    
    public Person findById(Long id) {
        Key<Person> key = new Key<Person>(Person.class, id);
        return ofy().get(key);
    }

    public ArrayList<Person> findAll() {
    	Objectify ofy = ObjectifyService.begin();
    	Query<Person> query = ofy.query(Person.class);
    	QueryResultIterator<Person> iterator = query.iterator();
    	ArrayList<Person> people = new ArrayList();
        while (iterator.hasNext()) {
            Person person = iterator.next();
            people.add(person);
        }
        return people; 
    }
    
    public void deleteAll() {
    	Objectify ofy = ObjectifyService.begin();
    	Iterable<Key<Person>> allKeys = ofy.query(Person.class).fetchKeys();
    	ofy.delete(allKeys);
        
    }

}
